package com.example.administrator.newxlmedical;

import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Message;
import android.os.Bundle;
import android.util.Log;

import com.example.administrator.baseproject.BaseActivity;
import com.irisian.irissdk.IrisSdk;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import beans.CabinetInfoBean;
import beans.CabinetInfoParentBean;
import beans.SupplierRightsBean;
import beans.UserInfoBean;
import constants.Constants;
import constants.HandlerConstant;
import customhandler.MyHandler;
//import dialogs.LoginDialog;
import netframe.GetRetrofit;
import netframe.MyAction1;
import netframe.NetAddress;
import beans.NewUserInfoBean;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.observables.GroupedObservable;
import rx.schedulers.Schedulers;
import singleton.SingletonClass;
import utils.ActivityControl;
import utils.ActivityUtil;
import utils.HardwareInfoUtils;
import utils.LoginRedCountUtils;
import utils.ObjectSaveUtil;
import utils.SharedPreferenceUtil;
import utils.ToastUtil;

public class BaseEnterActivity extends BaseActivity {
    //用于拼接所有的CabinetInfoId,方便sql语句(拼接终端下所有的CabinetInfoId)
    private StringBuilder sbCabinetInfoIds = new StringBuilder();
    //用来保存CabinetInfoId,和LogicNumber
    private Map<Integer, String> hashMap = new HashMap<>();
    //(拼接医药厂商可用的CabinetInfoId)
    private StringBuilder sbEnableLogicNumber = new StringBuilder();

    public SharedPreferences sharedPreferences;
    private int netWorkCount;
    private boolean isExitUser;//判断是否存在可用的用户
    private MyHandler allHandler;
    public static final int UNLOGIN_TIME = 30000;//登录超时时间
    private String cabinetInfoIds;
    //    private LoginDialog loginDialog;
    private long star;

    private NewUserInfoBean.DataBean userInfoBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void initView() {
        allHandler = SingletonClass.getSingleton(MyHandler.class);
        sharedPreferences = SharedPreferenceUtil.getSharedPreferences(BaseEnterActivity.this);
    }

    //获取数据库cabinetInfo表的id,医疗厂商的权限会用到(此时查出的是此终端下面的所有的cabinetinfoid)
    public void getCabinetInfoId() {
        String sql = "select * from CabinetInfo where TerminalInfoID = " + NetAddress.terminalInfoId;
        GetRetrofit.getInstance().getCabinetInfoId(NetAddress.token, NetAddress.machineCode, sql)
                .subscribeOn(Schedulers.io()).groupBy(new Func1<List<CabinetInfoBean>, Boolean>() {
            @Override
            public Boolean call(List<CabinetInfoBean> cabinetInfoBeen) {
                return cabinetInfoBeen == null ? false : cabinetInfoBeen.size() > 0;
            }
        }).flatMap(new Func1<GroupedObservable<Boolean, List<CabinetInfoBean>>, Observable<CabinetInfoBean>>() {
            @Override
            public Observable<CabinetInfoBean> call(GroupedObservable<Boolean, List<CabinetInfoBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.flatMap(new Func1<List<CabinetInfoBean>, Observable<CabinetInfoBean>>() {
                        @Override
                        public Observable<CabinetInfoBean> call(List<CabinetInfoBean> cabinetInfoBeen) {
                            CabinetInfoParentBean cabinetInfoParentBean = new CabinetInfoParentBean();
                            cabinetInfoParentBean.setCabinetInfoBeanList(cabinetInfoBeen);
                            ObjectSaveUtil.saveObject(BaseEnterActivity.this, cabinetInfoParentBean, Constants.CABINETINFO_PARENT_BEAN, Constants.CABINETINFO_PARENT_BEAN);
                            return Observable.from(cabinetInfoBeen).doOnNext(new Action1<CabinetInfoBean>() {
                                @Override
                                public void call(CabinetInfoBean cabinetInfoBean) {
                                    sbCabinetInfoIds.append(cabinetInfoBean.getID() + ",");
                                    hashMap.put(cabinetInfoBean.getID(), cabinetInfoBean.getLogicNumber());
                                }
                            }).last();
                        }
                    });
                } else {
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<CabinetInfoBean>() {
            @Override
            public void call(CabinetInfoBean cabinetInfoBean) {
                cabinetInfoIds = sbCabinetInfoIds.deleteCharAt(sbCabinetInfoIds.length() - 1).toString();
                //查找供应商可用的cabinetinfoid
                getEnableCabinetInfoId(cabinetInfoIds);
                ObjectSaveUtil.saveObject(BaseEnterActivity.this, hashMap, Constants.CABINETINFO_LOGICNUMBER_HASHMAP, Constants.CABINETINFO_LOGICNUMBER_HASHMAP);
            }
        }, new MyAction1());

}

    public void getEnableCabinetInfoId(final String cabinetInfoIds) {
        String sql = "select * from SupplierRights where DeleteFlag = 0 and CabinetInfoId in (" + cabinetInfoIds + ")";
        GetRetrofit.getInstance().getSupplierRights(NetAddress.token, NetAddress.machineCode, sql)
                .subscribeOn(Schedulers.io()).groupBy(new Func1<List<SupplierRightsBean>, Boolean>() {
            @Override
            public Boolean call(List<SupplierRightsBean> supplierRightsBeen) {
                return supplierRightsBeen == null ? false : supplierRightsBeen.size() > 0;
            }
        }).flatMap(new Func1<GroupedObservable<Boolean, List<SupplierRightsBean>>, Observable<SupplierRightsBean>>() {
            @Override
            public Observable<SupplierRightsBean> call(GroupedObservable<Boolean, List<SupplierRightsBean>> booleanListGroupedObservable) {
                if (booleanListGroupedObservable.getKey()) {
                    return booleanListGroupedObservable.flatMap(new Func1<List<SupplierRightsBean>, Observable<SupplierRightsBean>>() {
                        @Override
                        public Observable<SupplierRightsBean> call(List<SupplierRightsBean> supplierRightsBeen) {
                            return Observable.from(supplierRightsBeen).doOnNext(new Action1<SupplierRightsBean>() {
                                @Override
                                public void call(SupplierRightsBean supplierRightsBean) {
                                    sbEnableLogicNumber.append(hashMap.get(supplierRightsBean.getCabinetInfoId()) + ",");
                                }
                            }).last();
                        }
                    });
                } else {
                    //没有查询到权限,应该将权限清空
                    sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString(Constants.ENABLE_LOGICNUMBER, "");
                    edit.commit();
                    return null;
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<SupplierRightsBean>() {
            @Override
            public void call(SupplierRightsBean supplierRightsBean) {
                SharedPreferences.Editor edit = sharedPreferences.edit();
                edit.putString(Constants.ENABLE_LOGICNUMBER, sbEnableLogicNumber.toString());
                edit.commit();
                sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
            }
        }, new MyAction1());
    }

    //登录
    public void userLogin(final String sql, final int type) {
        star = System.currentTimeMillis();
        GetRetrofit.getInstance().getUserInfo2(NetAddress.token, NetAddress.machineCode, sql).subscribeOn(Schedulers.io())
                .groupBy(new Func1<NewUserInfoBean, Boolean>() {
                    @Override
                    public Boolean call(NewUserInfoBean newUserInfoBean) {
                        return newUserInfoBean == null ? false : newUserInfoBean.getData().size() > 0;
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap(new Func1<GroupedObservable<Boolean, NewUserInfoBean>, Observable<NewUserInfoBean.DataBean>>() {
                    @Override
                    public Observable<NewUserInfoBean.DataBean> call(GroupedObservable<Boolean, NewUserInfoBean> booleanUserInfoBeanGroupedObservable) {
                        if (booleanUserInfoBeanGroupedObservable.getKey()) {
                            return booleanUserInfoBeanGroupedObservable.observeOn(Schedulers.io())
                                    .flatMap(new Func1<NewUserInfoBean, Observable<NewUserInfoBean.DataBean>>() {
                                        @Override
                                        public Observable<NewUserInfoBean.DataBean> call(NewUserInfoBean newUserInfoBean) {
                                            return Observable.from(newUserInfoBean.getData()).last();
                                        }
                                    });
                        } else {
                            sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                            isExitUser = false;
                            ToastUtil.showToast(BaseEnterActivity.this, "该用户不存在");
                            if (type == 1) {
                                allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGER_LOGIN_NO_USER, 1000);
                            } else {
                                allHandler.sendEmptyMessageDelayed(HandlerConstant.IRIS_LOGIN_NO_USER, 1000);
                            }
                            return null;
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NewUserInfoBean.DataBean>() {
                    @Override
                    public void call(NewUserInfoBean.DataBean dataBean) {
                        userInfoBean = dataBean;
                        if (dataBean.isEnable() && dataBean.getDelFlag() == 0) {
                            isExitUser = true;
                            ObjectSaveUtil.saveObject(BaseEnterActivity.this, dataBean, Constants.USER_INFO_BEAN, Constants.USER_INFO_BEAN);

                        } else {
                            isExitUser = false;
//                            if (!dataBean.isEnable()) {
//                                ToastUtil.showToast(BaseEnterActivity.this, "该用户已被禁用");
//                            } else {
//                                ToastUtil.showToast(BaseEnterActivity.this, "该用户已被删除");
//                            }
                            if (type == 1) {
                                allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGER_LOGIN_ERROR, 1000);
                            } else {
                                allHandler.sendEmptyMessageDelayed(HandlerConstant.IRIS_LOGIN_ERROR, 1000);
                            }

                        }
                        sendEmptyMessage(HandlerConstant.FINISH_NETWORK);
                    }
                }, new MyAction1(){
                    @Override
                    public void call(Throwable throwable) {
                        super.call(throwable);
                        ToastUtil.showToast(BaseEnterActivity.this, "登录失败，请重试  " + throwable.getMessage() );
                        if (type == 1) {
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.FINGER_LOGIN_ERROR_AGIN, 1000);
                        } else {
                            allHandler.sendEmptyMessageDelayed(HandlerConstant.IRIS_LOGIN_ERROR_AGIN, 1000);
                        }
                    }
                });

    }

    @Override
    protected void onHandleMessage(Message msg) {
        switch (msg.what) {
            case HandlerConstant.FINISH_NETWORK:
                netWorkCount++;
                if (netWorkCount == 2) {
                    netWorkCount = 0;
                    if (isExitUser) {
                        final long end = System.currentTimeMillis();
                        Log.e(TAG, "login: " + (end - star));
                        String id;
                        if (userInfoBean.getRoleInfoId() != 1 && userInfoBean.getRoleInfoId() != 4){
                            id = "0";
                        }else {
                            id = userInfoBean.getID()+"";
                        }

                        LoginRedCountUtils.getLoginDataCount(BaseEnterActivity.this,id,NetAddress.deptCode,true);
//                        new HardwareInfoUtils().getRedDotCount(BaseEnterActivity.this);

                    } else {
                        sbCabinetInfoIds.delete(0, sbCabinetInfoIds.length());
                    }
                }
                break;

        }
    }
}
